package com.labbit.platform.manager.service.impl;

import com.labbit.platform.commons.domain.vo.PageInfoVO;
import com.labbit.platform.commons.exception.BusinessException;
import com.labbit.platform.commons.properties.CommonProperties;
import com.labbit.platform.commons.session.SessionData;
import com.labbit.platform.commons.session.SessionUtils;
import com.labbit.platform.commons.utils.IdGen;
import com.labbit.platform.commons.utils.MD5Util;
import com.labbit.platform.commons.utils.joda.JodaUtil;
import com.labbit.platform.manager.dao.AdminUserMapper;
import com.labbit.platform.manager.dao.RoleMapper;
import com.labbit.platform.manager.domain.bo.AdminUserBO;
import com.labbit.platform.manager.domain.po.AdminUser;
import com.labbit.platform.manager.domain.po.Role;
import com.labbit.platform.manager.domain.query.UserQuery;
import com.labbit.platform.manager.domain.vo.UserListVO;
import com.labbit.platform.manager.exception.LoginException;
import com.labbit.platform.manager.exception.UserException;
import com.labbit.platform.manager.exception.message.UserError;
import com.labbit.platform.manager.service.AdminUserService;
import com.labbit.platform.manager.utils.AccountUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

/**
 * @description:
 * @Author: CHEN YU
 * @Date: 2020-12-20 17:44
 **/
@Service
@Slf4j
public class AdminUserServiceImpl implements AdminUserService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private AdminUserMapper adminUserMapper;

    @Autowired
    private CommonProperties commonProperties;

    @Override
    public SessionData login(String username, String password) {
        AdminUser adminUser = adminUserMapper.selectForLogin(username, encodePassword(password));
        if (null == adminUser) {
            throw new LoginException(UserError.USER_OR_PASSWORD_NOT_MATCH);
        }
        SessionData sessionData = new SessionData();
        String token = UUID.randomUUID().toString();
        sessionData.setId(adminUser.getId());
        sessionData.setToken(token);
        sessionData.setDisplayName(adminUser.getAccountName());
        sessionData.setUsername(adminUser.getUsername());
        SessionUtils.putSession(token, sessionData);
        return sessionData;
    }


    @Override
    public void userRegister(AdminUserBO adminUserBO) {
        // 查询角色是否存在
        Role role = roleMapper.selectByPrimaryKey(adminUserBO.getRoleId());
        if (null == role) {
            throw new UserException(UserError.ROLE_NOT_FOUND);
        }
        //检查用户名是否存在
        Integer userCount = adminUserMapper.selectCountByUsername(adminUserBO.getUsername());
        if (userCount > 0) {
            throw new UserException(BusinessException.createMessage(UserError.USERNAME_EXIST, adminUserBO.getUsername()));
        }
        AdminUser user = new AdminUser();
        user.setId(IdGen.getId());
        user.setCreatedBy(SessionUtils.getCurrentUserId());
        user.setCreatedDate(JodaUtil.getNowDate());
        user.setAccountName(adminUserBO.getAccountName());
        user.setUsername(adminUserBO.getUsername());
        user.setPassword(encodePassword(adminUserBO.getPassword()));
        user.setRoleId(adminUserBO.getRoleId());
        user.setAccountId(increaseAccountId());
        adminUserMapper.insertSelective(user);

    }


    @Override
    public PageInfoVO<UserListVO> userList(UserQuery userQuery) {
        PageInfoVO.startPage(userQuery);
        List<UserListVO> userListVOS = adminUserMapper.selectUserList(userQuery.getAccountName());
        for (UserListVO userListVO : userListVOS) {
            userListVO.setAccountId(AccountUtils.showAccountId(userListVO.getAccountId()));
        }
        return PageInfoVO.getInstance(userListVOS);
    }


    @Override
    public void deleteUser(String userId) {
        adminUserMapper.deleteByPrimaryKey(userId);
    }

    @Override
    public void updateUser(AdminUserBO adminUserBO) {
        AdminUser user = new AdminUser();
        user.setId(adminUserBO.getId());
        user.setUsername(adminUserBO.getUsername());
        user.setPassword(encodePassword(adminUserBO.getPassword()));
        user.setAccountName(adminUserBO.getAccountName());
        user.setRoleId(adminUserBO.getRoleId());
        user.setUpdatedBy(SessionUtils.getCurrentUserId());
        user.setUpdatedDate(JodaUtil.getNowDate());
        adminUserMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public AdminUserBO getUserInfoById(String id) {
        AdminUser user = adminUserMapper.selectByPrimaryKey(id);
        AdminUserBO userBO = new AdminUserBO();
        userBO.setId(user.getId());
        userBO.setUsername(user.getUsername());
        userBO.setAccountName(user.getAccountName());
        userBO.setRoleId(user.getRoleId());
        userBO.setAccountId(AccountUtils.showAccountId(user.getAccountId()+""));
        return userBO;
    }

    /**
     * @Description 密码加密
     * @Date 12/25/20 6:35 PM
     * @Author CHEN YU
     **/
    private String encodePassword(String password) {
        return MD5Util.encodeMD5Hex(password + commonProperties.getPasswordSalt());
    }

    private synchronized Integer increaseAccountId() {
        return adminUserMapper.selectCurrentAccountId()+1;
    }
}
